package dl.bukkit.myststus.api.listener;

import dl.bukkit.myststus.MyStatus;
import dl.bukkit.myststus.api.event.ReloadEvent;
import dl.bukkit.myststus.api.playerdata.ClientSizeData;
import dl.bukkit.myststus.configuration.imp.Config;
import lk.vexview.api.VexViewAPI;
import lk.vexview.hud.MinecraftHud;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.ArrayList;
import java.util.Map;

public class PlayerListener implements IListener {

    private final MyStatus plugin;

    public PlayerListener(MyStatus plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    void on(PlayerJoinEvent event) {
        set(event.getPlayer());
    }

    @EventHandler
    void on(ReloadEvent event) {
        new ArrayList<>(Bukkit.getOnlinePlayers()).forEach(this::set);
    }

    @EventHandler
    void on(PlayerQuitEvent event) {
        ClientSizeData.leaveServer(event);
    }

    private void set(Player player) {
        Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
            for (Map.Entry<MinecraftHud, Boolean> entry : Config.getInst().getMinecraftHudMap().entrySet()) {
                VexViewAPI.setMinecraftHudVisible(entry.getKey(), entry.getValue(), player);
            }
        });
    }

    @Override
    public boolean isRegister() {
        return true;
    }
}
